dojo.provide("uws.drawing.SortOrderManager");

dojo.declare('uws.drawing.SortOrderManager',null,{
	/*
		It provides services so that the sort order numbering of components are always in sync with what is displayed on the screen.
	*/
	counter:null,
	
	constructor:function(){
		this.counter = [];
	},
	addSurface:function(surfaceId, offset){
		if(offset){
			this.counter[surfaceId] = offset;
		}else{
			this.counter[surfaceId] = 0;
		}
	},
	getSortOrder:function(surfaceId){
		dataStore.fetchItemByIdentity({
			identity: surfaceId,
			scope:this,
			onItem: function(item){
				dataStore.setValue(item,"sort_order", this.counter[surfaceId]+1);
			},
			onError:function(e){
				console.debug(e);
			}
		});
		
		return this.counter[surfaceId]++;
	},
	repairSortOrder:function(surface, component, direction){
		dataStore.fetchItemByIdentity({
			identity: surface.id,
			scope: this,
			onItem: function(item){
				var comp = dataStore.getValues(item,"children");
				
				for(var i=0; i<comp.length;i++){
					for(var j=0; j<comp.length;j++){
						if(dataStore.getValue(comp[i], "sortOrder") > dataStore.getValue(comp[i], "sortOrder")){
							var temp = comp[i];
							comp[i] = comp[j];
							comp[j] = temp;
						}
					}
				}
				
				for(var i=0, so=1; i<comp.length;i++){
					if(dataStore.getValue(comp[i], "id") != component.id){
						if(direction=="front"){
							dataStore.setValue(comp[i], "sortOrder", (so-1));
						}else{
							dataStore.setValue(comp[i], "sortOrder", so);
						}
						so++;
					}else{
						if(direction=="front"){
							dataStore.setValue(comp[i], "sortOrder", (comp.length-1));
						}else{
							dataStore.setValue(comp[i], "sortOrder", 0);
						}
					}
				}
				
				dataStore.setValue(item, "sort_order", comp.length);
				this.counter[surface.id] = comp.length;
			},
			onError:function(e){
				console.debug(e);
			}
		});
	}
});